package com.wct.jms;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;

import java.nio.ByteBuffer;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.ObjectMessage;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.bson.BSONObject;

import com.sequoiadb.base.DBCollection;
import com.sequoiadb.base.DBCursor;
import com.sequoiadb.base.Sequoiadb;
import com.sequoiadb.base.SequoiadbDatasource;
import com.sequoiadb.exception.BaseException;
import com.wct.EchoServer;
import com.wct.db.DbUtils;
import com.wct.struct.SyscfgPacket;
import com.wct.util.PackageBuilder;

public class ConsumerMessageListener implements MessageListener {
	private final Logger logger = LogManager.getLogger(ConsumerMessageListener.class);
	
	private PackageBuilder builder;
	public void onMessage(Message message) {
		try {
			ObjectMessage objMessage = (ObjectMessage) message;
			JMSMessage jmsMessage = (JMSMessage) objMessage.getObject();
			String identity = EchoServer.deviceid2ip.get(jmsMessage.getDeviceId());
			ChannelHandlerContext context = null;
			if (identity!=null) {
				context = EchoServer.connectionMap.get(identity);
            }

			switch (jmsMessage.getType()) {
			case APP_EDITDEVICEINFO:
				if (context != null) {																		
					ByteBuffer buff = builder.MakeDefaultSyscfgFromDevice(jmsMessage.getDeviceId());
					if (buff != null) {
						buff.position(0);
						ByteBuf resp = Unpooled.copiedBuffer(buff);
						context.write(resp);
						context.flush();	
						logger.info("send syscfg to client");
                    }
				}
				break;
			case APP_GETGPSMANUAL:
				if (context != null) {																		
					ByteBuffer buff = builder.MakeSyscfgFromDevice(jmsMessage.getDeviceId(), (short)1, (short)0);
					if (buff != null) {
						buff.position(0);
						ByteBuf resp = Unpooled.copiedBuffer(buff);
						context.write(resp);
						context.flush();	
						logger.info("send syscfg to client");
                    }
				}
				break;
			default:
				logger.info("unhanled message type " + jmsMessage.getType().name());
				break;
			}
		} catch (JMSException | BaseException   e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public PackageBuilder getBuilder() {
		return builder;
	}
	public void setBuilder(PackageBuilder builder) {
		this.builder = builder;
	}
	
}
